#include "sendmsg.h"

#include<string>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#define MAXLINE 50

    int    sockfd, n;
    char  sendline[30];
    struct sockaddr_in servaddr;

void encoding(char *p,int* motion){
    short* it=(short*)p;
    for(int i=0;i<20;i++){
        *it=motion[i];
        it++;
    }
}
void decoding(char *p,int* motion){
    short* it=(short*)p;
    for(int i=0;i<20;i++){
        motion[i]=*it;
        it++;
    }
}
void encilentcoding(std::string cmd,int t,int* motion,char *data)//cmd
{
    for(int i=0;i<3;i++)
        data[i]=cmd[i];
    data[3]='\0';
    for(int i=0;i<4;i++)
        data[i+4]=((char *)&t)[i];
    data[8]='\0';
    encoding(data+9,motion);

}
void disconnect(){
    printf("\n************************socket closed!!!!\n");
close(sockfd);
}
void connect_init(){

 if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
    printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);
    exit(0);
    }
    memset(&servaddr, 0, sizeof(servaddr));
     memset(sendline, 0, sizeof(sendline));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(6666);
    char * ip="127.0.0.1";
    if( inet_pton(AF_INET, ip ,&servaddr.sin_addr) <= 0){
    printf("inet_pton error for %s\n","local");
    exit(0);
    }

    if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){
    printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
    exit(0);
    }
    else
        printf("\nsocket connected !!!!!!!!!!!!!!!!!!!!\n********************---------------------\n");
    }
void send_msg(int data[20]){
    int tesm[20];
        encilentcoding("beg",125,data,sendline);
        decoding(sendline+9,tesm);
        if( send(sockfd, sendline, MAXLINE, 0) < 0)
        {
        printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
        exit(0);
        }
}


